﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Redbrick.Silverlight.Extentions
{
	public static class Collections
	{
		/// <summary>
		/// add a range to an observable collection
		/// </summary>
		public static ObservableCollection<_type> AddRange<_type>(this ObservableCollection<_type> oc, IEnumerable<_type> data)
		{
			foreach (_type cur in data)
				oc.Add(cur);
			return oc;
		}

		/// <summary>
		/// for each element in the OC, run the function
		/// </summary>
		public static ObservableCollection<_type> ForEach<_type>(this ObservableCollection<_type> oc, Action<_type> action)
		{
			foreach (_type cur in oc)
			{
				action(cur);
			}
			return oc;
		}
		/// <summary>
		/// for each item in the IEnumerable, run the action 
		/// </summary>
		public static void ForEach<_type>(this IEnumerable<_type> itemList, Action<_type> action)
		{
			foreach (_type itm in itemList)
				action(itm);
		}
		/// <summary>
		/// for each item in the IEnumerable, run the action 
		/// </summary>
		public static void ForEach<_type>(this IEnumerable itemList, Action<_type> action)
		{
			foreach (_type itm in itemList)
				action(itm);
		}

		/// <summary>
		/// convert the IEnumerable to an OC
		/// </summary>
		public static ObservableCollection<_type> ToObservableCollection<_type>(this IEnumerable<_type> items)
		{
			return new ObservableCollection<_type>(items);
		}
		/// <summary>
		/// convert the IEnumerable to an OC
		/// </summary>
		public static ObservableCollection<_type> ToObservableCollection<_type>(this IEnumerable items)
		{
			ObservableCollection<_type> oc = new ObservableCollection<_type>();
			items.ForEach<_type>((itm) => oc.Add(itm));
			return oc;
		}

		/// <summary>
		/// search an IEnumerable by using a predicate
		/// </summary>
		public static bool Has<_type>(this IEnumerable<_type> items, Func<_type, bool> predicate)
		{
			if (items == null) return false;
			if (items.Count() == 0) return false;
			foreach (_type item in items)
				if (predicate(item)) return true;
			return false;
		}

	}
}
